/* axoios 封装 */
import axios, {AxiosError, AxiosPromise, AxiosResponse} from 'axios';
import {ElNotification} from 'element-plus';
import router from '@/router';
import {useMainStore} from '@/stores/mainStore';
import {useAuthUserStore} from '@/stores/authuserStore';
import {reactive} from 'vue';
import utils from '../utils';
import Cookies from 'js-cookie'

// 通用错误状态码提示
const tips: any = {
	1: '服务请求超时，请检查您的网络！',
	404: '无效的请求！',
	408: '请求超时！',
	409: '请求冲突！',
	422: '无法处理的实体!',
	500: '服务器内部错误',
	502: '网关错误。',
	503: '服务不可用，服务器暂时过载或维护。',
	504: '网关超时。',
	507: '服务器内部错误',
};


const _cacheState = reactive({
	timer: false,
})

// 需要处理的 400 错误状态码
const tip_super: Array<number> = [400, 401, 402, 403];


class HTTP {
	request(params: any): AxiosPromise<any> {
		if (!params.method) {
			params.method = 'GET';
		}
		const mainStore = useMainStore();
		// create an axios instance
		const service = axios.create({
			baseURL: params.v ? import.meta.env.VITE_APP_URL + params.v : import.meta.env.VITE_APP_URL + mainStore.apiVerson,
			timeout: 50000, // 请求超时时间
		});

		// 请求拦截器
		service.interceptors.request.use(
			(config: any) => {
				config.timeout = 50000;
				// config.headers['Content-Type'] = 'application/form-data';
				if (Cookies.get('token')) {
					config.headers['Authorization'] = 'Bearer ' + Cookies.get('token');
				}
				return config;
			},
			(error: any) => {
				console.log(error);
				return Promise.reject(error);
			}
		);

		// 响应拦截器
		service.interceptors.response.use(
			(response: AxiosResponse) => {
				if (["用户未登录，请先登录", "Signature has expired.", 'token失效'].includes(response.data.msg)) {
					ElNotification({
						title: '提示',
						message: '登录失效，请重新登录',
						type: 'warning',
					})
					Cookies.remove('token');
					window.open('/student/Login','_self')
					// this.router.push('/Login')
				} else {
					return response;
				}
			},
			(error: AxiosError) => {
				let err_code = error.response?.status || 1;
				tip_super.indexOf(err_code) === -1 ? this._deal_error(err_code) : this._deal_400_error(error.response);
				return {ResponseError: true};
			}
		);
		if (params.file) {
			const formData = new FormData();
			formData.append('file', params.file);
			return service({
				...params,
				method: 'POST',
				data: formData,
				headers: {
					...params.headers,
					'Content-Type': 'multipart/form-data',
				},
			});
		} else {
			return service(params);
		}
	}

	_deal_400_error(res: AxiosError["response"]) {
		if (res?.status === 401) {
			console.log("进入401啦")
			console.log(res)
			if (res.data?.message === 'Signature has expired.') {
				this._el_notification('认证失效，请重新登录！');
				Cookies.remove('token');
				window.open('/student/Login','_self')
			}

			if (res.data?.message === 'login required') {
				this._el_notification('认证失效，请重新登录！');
				Cookies.remove('token');
				window.open('/student/Login','_self')
			}

			if (res.data?.message === 'Token is invalid or expired.') {
				this._el_notification('认证失效，请重新登录！');
				Cookies.remove('token');
				window.open('/student/Login','_self')
			}


		}
		if (res?.status === 403) {
			// 无权限
			if (res.data?.detail === 'Given token not valid for any token type') {
				window.open('/student/Login','_self')
				this._el_notification('认证失效，请重新登录！');
			}
		}
		Object.values(res?.data).forEach((item: any) => {
			this._el_notification(Array.isArray(item) ? item[0] : item);
		});
	}

	_deal_error(error_code: string | number) {
		error_code = error_code + '' || '1';
		if (Object.keys(tips).indexOf(error_code) !== -1) {
			this._el_notification(tips[error_code]);
		} else {
			// 特殊状态码处理
		}
	}

	_el_notification(message: string) {
		// 弹窗 1秒 防抖
		!_cacheState.timer && (
			(_cacheState.timer = true),
				ElNotification({message: message, type: 'error',}),
				utils.cacheTime(() => (_cacheState.timer = false), 1000)
		)
	}


}

export default HTTP;
